package com.kung.qvs.ui.main.fragment;

import android.app.Application;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;


import com.google.gson.Gson;
import com.kung.qvs.data.JtRepository;
import com.kung.qvs.entity.BaseResultBean;
import com.kung.qvs.entity.ProductBean;
import com.kung.qvs.entity.ProductInfoBean;
import com.kung.qvs.entity.PropInfoBean;
import com.kung.qvs.entity.ReqAddDeivceBean;
import com.kung.qvs.entity.ResSetInfoBean;
import com.kung.qvs.entity.WorkerBean;
import com.kung.qvs.entity.database.SqlManager;
import com.kung.qvs.ui.login.LoginActivity;
import com.kung.qvs.ui.main.HomeActivity;
import com.kung.qvs.utils.Constants;
import com.tencent.bugly.proguard.B;

import java.net.URL;
import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.http.BaseResponseBean;
import me.goldze.mvvmhabit.http.ResponseThrowable;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.StringUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class SettingViewModel extends BaseViewModel<JtRepository> {

    public ObservableField<String> versionName = new ObservableField<>("");
    public ObservableField<Integer> versionCode = new ObservableField<>(0);
    public ObservableField<String> forgName = new ObservableField<>(Constants.forg_name);
    public ObservableField<String> equipmentNo = new ObservableField<>("");

    public ObservableField<CharSequence> mHtml = new ObservableField<>();

    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();

    public ObservableField<Integer> visible = new ObservableField<>(View.VISIBLE);

    public class UIChangeObservable {
        //下拉刷新完成
        public SingleLiveEvent eventToLoginPage = new SingleLiveEvent<>();
        public SingleLiveEvent eventToCompanyInfo = new SingleLiveEvent<>();
        public SingleLiveEvent eventToSetBaseUrl = new SingleLiveEvent();   //设置请求ip地址
        public SingleLiveEvent eventToExitApp = new SingleLiveEvent();
        public SingleLiveEvent eventToResetPwd = new SingleLiveEvent();
        public SingleLiveEvent eventToSupplierPage = new SingleLiveEvent();
        public SingleLiveEvent eventToCustomerPage = new SingleLiveEvent();
        public SingleLiveEvent eventToManageProduct = new SingleLiveEvent();

    }

    public SettingViewModel(@NonNull Application application, JtRepository model) {
        super(application, model);
    }

    private PropInfoBean propInfoBean1; //下载的公司信息

    @Override
    public void onCreate() {
        super.onCreate();
//        propInfoBean1 = SqlManager.queryPropInfoBeanById(Constants.LOCAL_CODE_DEFAULT);
//        if (propInfoBean1 != null) {
//            forgName.set(propInfoBean1.getProducer());
//        }
    }

    @Override
    public void onResume() {
        super.onResume();
        equipmentNo.set(model.getEquipmentNo());
        if (model.getLoginType().equals(Constants.LOGIN_TYPE_WORKER)) {
            visible.set(View.GONE);
        } else {
            visible.set(View.VISIBLE);
        }
    }

    //产品管理页面
    public BindingCommand onCommandManageProduct = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uc.eventToManageProduct.call();
        }
    });

    public BindingCommand onCommanSetBaseUrl = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uc.eventToSetBaseUrl.call();
        }
    });

    public BindingCommand onCommanBack = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uc.eventToLoginPage.call();
        }
    });

    public BindingCommand onCommandUpdateCompany = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uc.eventToCompanyInfo.call();
        }
    });

    public BindingCommand onCommandSyncWorkers = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            funLoadWorkers();
        }
    });

    public BindingCommand onCommandSyncCompany = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            doGetPropInfo(model.getEquipmentNo());
        }
    });

    public BindingCommand onCommandEditSupplier= new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uc.eventToSupplierPage.call();
        }
    });

    public BindingCommand onCommandEditCustomer = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uc.eventToCustomerPage.call();
        }
    });

    public BindingCommand onCommandResetPwd = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uc.eventToResetPwd.call();
        }
    });

    public BindingCommand onCommanExitApp = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uc.eventToExitApp.call();
        }
    });

    public String getBaseUrl() {
        return model.getBaseUrl();
    }
    public void setBaseUrl(String baseUrl) {
        model.saveBaseUrl(baseUrl);
    }


    public void doFunExit() {
        //退出
        model.saveLoginState(false);
        model.saveKeepPwd(false);
        //进入DemoActivity页面
        startActivity(LoginActivity.class);
        //关闭页面
        finish();
    }

    //初始化垃圾类型
    public void funLoadWorkers() {
        model.reqSynchronizePackers("", model.getEquipmentNo(), "3", "").compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog("正在请求数据...");
                    }
                })
                .subscribe(new DisposableObserver<BaseResultBean<List<WorkerBean>>>() {
                    @Override
                    public void onNext(BaseResultBean<List<WorkerBean>> response) {
                        //请求成功
                        if (response.isSuccess()) {
                            //数据插入本地，并根据id排序查询。已被无网络情况使用
                            SqlManager.deleteWorkerBeans();
                            for(WorkerBean bean : response.entity) {
                                SqlManager.insertOrReplaceWorkerBean(bean);
                            }
                            ToastUtils.showShort("更新员工信息成功");
                        } else {
                            //code错误时也可以定义Observable回调到View层去处理
                            ToastUtils.showShort(response.desc);
                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        //关闭对话框
//                        dismissDialog();
                        if (throwable instanceof ResponseThrowable) {
                            ToastUtils.showShort(((ResponseThrowable) throwable).message);
                            //token失效，重新登录
//                            finish();
                            //如果无网络，使用本地缓存垃圾分类
                        }
                    }

                    @Override
                    public void onComplete() {
                        //关闭对话框
                        dismissDialog();
                    }
                });
    }

    //企业信息下载
    private void doGetPropInfo(String equipmentNo) {

//        model.doGetPropInfo(equipmentNo).compose(RxUtils.schedulersTransformer()) //线程调度
//                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
//                .doOnSubscribe(this)//请求与ViewModel周期同步
//                .doOnSubscribe(new Consumer<Disposable>() {
//                    @Override
//                    public void accept(Disposable disposable) throws Exception {
//                        showDialog("正在请求数据...");
//                    }
//                })
//                .subscribe(new DisposableObserver<BaseResponseBean<PropInfoBean>>() {
//                    @Override
//                    public void onNext(BaseResponseBean<PropInfoBean> response) {
//                        //请求成功
//                        if (response.isOk()) {
//                            PropInfoBean bean = response.getData();
//                            bean.set_id(null);
//                            bean.setLocalId(Constants.LOCAL_CODE_DEFAULT);
//                            SqlManager.insertOrReplacePropInfoBean(bean);
//                            ToastUtils.showShort("更新企业信息成功");
//                        } else {
//                            ToastUtils.showShort(response.getMessage());
//                        }
//                    }
//
//                    @Override
//                    public void onError(Throwable throwable) {
//                        //关闭对话框
////                        dismissDialog();
//                        if (throwable instanceof ResponseThrowable) {
//                            ToastUtils.showShort(((ResponseThrowable) throwable).message);
//                        }
//                    }
//
//                    @Override
//                    public void onComplete() {
//                        //关闭对话框
//                        dismissDialog();
//                    }
//                });
    }


}
